#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

void do_get(int newfd,char* cmd)
{
	char* filename;
	int filefd;
	int filesize,n;
	char buf[BUFSIZ];//8KB
	char* retinfo;
	
	/*查询文件是否存在*/
	strtok(cmd," ");
	filename = strtok(NULL," ");
	filename[strlen(filename)-1] = '\0';//把末尾的'\n'去掉
	filefd = open(filename,O_RDONLY);
	if(filefd < 0)
	{
		perror("open");
		retinfo = "NO";
		write(newfd,retinfo,strlen(retinfo));
		return;
	}
	retinfo = "YES";
	write(newfd,retinfo,strlen(retinfo));
	
	/*发送文件*/
	//计算文件大小
	filesize = lseek(filefd,0,SEEK_END);//把位置指针移到文件末尾，并读取此时的字节数即文件大小
	lseek(filefd,0,SEEK_SET);//把位置指针重置到文件开头
	printf("filesize:%d\n",filesize);
	
	//复制
	n = filesize/BUFSIZ;
	while(n--)
	{
		if(read(filefd,buf,BUFSIZ) == BUFSIZ)
		{
			write(newfd,buf,BUFSIZ);
			bzero(buf, BUFSIZ);
			filesize = filesize -BUFSIZ;
			usleep(100000);//延时，避免粘包
		}
		else
			printf("服务器发送文件时出错！\n");
	}

	if(filesize > 0)
	{
		read(filefd,buf,filesize);
		write(newfd,buf,filesize);
	}

	/*关闭文件*/
	close(filefd);
	printf("服务器发送文件已完成。\n");

	/*挂电话*/
	close(newfd);	
}

